package top.littlefogcat.shuzihuarongdao.main;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import top.littlefogcat.shuzihuarongdao.MenuActivity;
import top.littlefogcat.shuzihuarongdao.highscore.HighScore;
import top.littlefogcat.shuzihuarongdao.R;
import top.littlefogcat.shuzihuarongdao.server.MusicService;
import top.littlefogcat.shuzihuarongdao.server.MyServer2;
import top.littlefogcat.shuzihuarongdao.suanfa.demo;
//import top.littlefogcat.shuzihuarongdao.suanfa.ret;

public class GameActivity extends AppCompatActivity {
    private Handler mHandler = new Handler();
    private static final String TAG = "GameActivity";
    private int seconds = 0;
    private boolean running = true; //计时状态

    private TextView mStep;
    private TextView mMaskView;
    private TextView tv_tipsOfNext;
    private BoardView mBoardView;
    private TextView mCheat;
    private int mCheatCount = 0;
    private long mLastCheatTime;
    private int mDownNumber = 4;
    private long mStartTime;
    private long mEndTime;
    private Button sto;
    private TextView tttt;

    private int tipsOgNextIndex = 0;
    private ArrayList<Integer> tipsOfNext;

    /**
     * 高分排行榜
     */
    private List<HighScore> mHighScoreList;

    private SharedPreferences mPref;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Intent b = new Intent(GameActivity.this, MyServer2.class);
        startService(b);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        runTime();
//        best();

        mStep = findViewById(R.id.step);
        mMaskView = findViewById(R.id.mask);
        mBoardView = findViewById(R.id.board);
        mCheat = findViewById(R.id.tvCheat);
        tttt = findViewById(R.id.sssst);
        sto=findViewById(R.id.st);
        tv_tipsOfNext = findViewById(R.id.next78);


        mCheat.setOnClickListener(v -> {

            if (mLastCheatTime == 0 || mLastCheatTime - System.currentTimeMillis() > 1000) {
                mLastCheatTime = System.currentTimeMillis();
                mCheatCount = 0;
            } else if (mCheatCount < 10) {
                mCheatCount++;
            } else {
                saveHighScore(30000, 999);
            }


        });


        mBoardView.setBoardViewListener(new OnBoardViewListener() {


            @Override
            public void onViewCreated(Boolean isViewCreated) {
            }

            @Override
            public void onChildViewMoved() {
                tipsOgNextIndex++;
                tv_tipsOfNext.setText("提示下一步："+ tipsOfNext.get(tipsOgNextIndex));

            }

            @Override
            public void onGameFinished(int step) {
                mEndTime = System.currentTimeMillis();
                long useTime = mEndTime - mStartTime;
                saveHighScore(useTime, step);
            }

            @Override
            public void onStepAdded(int step) {
                //步数增加回调此方法
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mStep.setText("当前步数:" + step);
                    }
                });
            }
        });
        mPref = PreferenceManager.getDefaultSharedPreferences(this);
        startGenerateBoard();
        loadHighScore();


//        sto.setOnClickListener(v -> {
//
//
//            mStep.setText(String.valueOf(new ret().getAp()));
//
//
//        });
    }

    public void startGenerateBoard() {
        int sizeX = mBoardView.getSizeX();
        int sizeY = mBoardView.getSizeY();
        BoardGenerator generator = new BoardGenerator(sizeX, sizeY);
        generator.setOnGeneratedListener(board -> mHandler.post(() -> {
            List<Integer> data = new ArrayList<>();
            for (int[] line : board) {
                for (int aInt : line) {
                    data.add(aInt);
                }
            }
            mBoardView.setData(data);
            startGame();
        }));
        new Thread(generator::generate).start();

    }

    private void loadHighScore() {
        String highScoreJson = mPref.getString(getString(R.string.pref_key_high_score), null);
        Log.d(TAG, "loadHighScore: " + highScoreJson);
        if (highScoreJson != null) {
            Gson gson = new Gson();
            mHighScoreList = gson.fromJson(highScoreJson, new TypeToken<List<HighScore>>() {
            }.getType());
        } else {
            mHighScoreList = new ArrayList<>();
        }
        Log.d(TAG, "loadHighScore: " + mHighScoreList);
    }

    private void saveHighScore(long useTime, int step) {
        if (mHighScoreList == null) {
            return;
        }
        int highScoreCount = mHighScoreList.size();
        int scoreRank = -1;
        if (mHighScoreList.size() == 0) {
            scoreRank = 0;
        } else {
            for (int i = 0; i < highScoreCount; i++) {
                HighScore score = mHighScoreList.get(i);
                if (useTime < score.useTime) {
                    scoreRank = i;
                    break;
                }
            }
        }
        if (scoreRank == -1) {
            new AlertDialog.Builder(this)
                    .setTitle("恭喜完成")
                    .show();
            return;
        }

        HighScore newScore = new HighScore();
        newScore.useTime = useTime;
        newScore.time = mEndTime;
        newScore.useStep = step;
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("恭喜打破记录！");
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_high_score, null, false);
        EditText et = contentView.findViewById(R.id.etName);
        TextView tv = contentView.findViewById(R.id.tvUseTime);
        String msg = "用时" + useTime / 1000 + "秒，排名第" + (scoreRank + 1);
        tv.setText(msg);
        dialog.setView(contentView);
        int rank = scoreRank;
        dialog.setPositiveButton("确定", (d, which) -> {
            String name = et.getText().toString();
            if (name.length() == 0) {
                name = "匿名";
            }
            newScore.name = name;
            mHighScoreList.add(rank, newScore);
            while (mHighScoreList.size() > 10) {
                mHighScoreList.remove(10);
            }
            Gson gson = new Gson();
            String json = gson.toJson(mHighScoreList);
            mPref.edit().putString(getString(R.string.pref_key_high_score), json).apply();
        });
        dialog.setCancelable(false);
        dialog.show();
        running=false;
    }

    private void startGame() {
        mMaskView.setVisibility(View.GONE);
        mStartTime = System.currentTimeMillis();

        demo d = new demo();
        int endStep = d.suanfa();
        tipsOfNext = d.getTipsOfNext();
        tttt.setText("最优解:"+endStep);
        tv_tipsOfNext.setText("提示下一步："+ tipsOfNext.get(tipsOgNextIndex));

//        HashMap<Integer,String> data = new demo().suanfa();
//        Set<Integer> key = data.keySet();
//        for (Integer integer : key) {
//            tttt.setText("key:"+integer+"value:"+data.get(integer));
//        }
//        tttt.setText("最优解:"+String.valueOf(a));
    }

    protected void onStop(){
        Intent intt = new Intent(GameActivity.this,MyServer2.class);
        stopService(intt);
        running=false;
        super.onStop();
    }
    protected  void onResume(){
        Intent ab = new Intent(GameActivity.this, MyServer2.class);
        startService(ab);
        running=true;
        super.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        running = false;
    }

    private void runTime() {
        final Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                final TextView textView = findViewById(R.id.timeView);
                int hour = seconds / 3600 % 24;
                int minute = seconds % 3600 / 60;
                String time = String.format("%02d:%02d:%02d", hour, minute, seconds % 60);
                textView.setText(time);
                if (running) seconds++;
                handler.postDelayed(this, 1000);
            }
        });
    }

}
